package com.cj.exception;

import com.cj.pojo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException e) {
        logger.error("业务异常 - 错误码: {}, 错误信息: {}, 详情: {}", 
            e.getErrorCode().getCode(), 
            e.getErrorCode().getMessage(),
            e.getDetail());
            
        String message = e.getErrorCode().getMessage();
        if (e.getDetail() != null && !e.getDetail().isEmpty()) {
            message += ": " + e.getDetail();
        }
        return Result.error(e.getErrorCode().getCode(), message);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return Result.error(ErrorCode.PARAM_INVALID.getCode(), "请求参数格式错误");
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        logger.error("系统异常: {}", e.getMessage(), e);
        return Result.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统繁忙，请稍后再试");
    }
}
